package com.hepinghospital.user.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.EmsListAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.ui.widget.StepView;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.EMSResponse;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.UtilList;

/**
 * Description
 * Created by lbj on 2021/8/27 10:00
 */

public class AtyLogisticsActivity extends BaseActivity {

    @BindView(R.id.stepView)
    StepView stepView;
    @BindView(R.id.activity_main)
    LinearLayout activityMain;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rv_ems)
    RecyclerView rvEms;
    private String prescriptionId;
    List<EMSResponse> mLists = new ArrayList<>();
    private static final String PATTERN_PHONE = "((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(166)|(17[0-8])|(18[0,5-9])|(19[8-9])|(14[5-9]))\\d{8}";
    private static final String SCHEME_TEL = "tel:";
    private EmsListAdapter emsListAdapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_logistics;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        tvTitle.setText("查看物流");
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvEms.setLayoutManager(manager);
        emsListAdapter = new EmsListAdapter(this, mLists);
        rvEms.setAdapter(emsListAdapter);
    }

    @Override
    protected void initData() {
        prescriptionId = getIntent().getStringExtra("prescriptionId");
//        String logistics = getIntent().getStringExtra("logistics");
//        tvCode.setText(waybillNo);
//        tvName.setText(logistics);
        queryResponseList();

    }

    private void queryResponseList() {
        showLoadingDialog(mContext);
        RestProxy.getInstance().queryResponseList(prescriptionId, new Observer<List<EMSResponse>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
            @Override
            public void onNext(List<EMSResponse> emsResponse) {
                dismissLoadingDialog();
                LogUtil.d("--大小",emsResponse.size()+"");
              if (!UtilList.isEmpty(emsResponse)){
                  mLists.clear();
                  mLists.addAll(emsResponse);
                  emsListAdapter.notifyDataSetChanged();
              }


            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

//    private void queryResponseList() {
//        showLoadingDialog(mContext);
//        RestProxy.getInstance().queryResponseList(waybillNo, new Observer<List<EMSResponse>>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @SuppressLint("SetTextI18n")
//            @Override
//            public void onNext(List<EMSResponse> emsResponse) {
//                List<EMSResponse> baseLists = emsResponse;
//                if (!UtilList.isEmpty(baseLists)) {
//                    for (int i = 0; i < baseLists.size(); i++) {
//                        List<EMSResponse.Logistics> logisticsList = baseLists.get(i).list;
//
//                        if (!UtilList.isEmpty(logisticsList)) {
//
//                            for (int j = 0; j < logisticsList.size(); j++) {
//                                StepItemData data = new StepItemData();
//                                data.setMsg("[" + logisticsList.get(j).opOrgCity + "]" + logisticsList.get(j).opDesc);
//                                data.setDate(baseLists.get(i).name + " " + logisticsList.get(j).opTime);
//                                datas.add(data);
//                            }
//                        } else {
//                            StepItemData data = new StepItemData();
//                            data.setMsg("[" + baseLists.get(i).name + "]");
//                            data.setDate(baseLists.get(i).name);
//                            datas.add(data);
//                        }
//
//                    }
//                }
//
//                new Handler().postDelayed(() -> {
//                    dismissLoadingDialog();
//                    // 指定数据集合
//                    stepView.setDatas(datas);
//                    // 设置view的绑定监听
//                    stepView.setBindViewListener((itemMsg, itemDate, data) -> {
//                        StepItemData sid = (StepItemData) data;
//                        itemMsg.setText(formatPhoneNumber(itemMsg, sid.getMsg()));
//                        itemDate.setText(sid.getDate());
//                    });
//                }, 2000);
//
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                ToastUtil.onError(mContext, e);
//            }
//
//            @Override
//            public void onComplete() {
//
//            }
//        });
//    }


    private void setStatusColor(TextView tvStatus, String status) {
        switch (status) {
            case "5":
            case "7":
            case "11":
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.ff999999));
                break;

            default:
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.fff54c4c));
        }
    }


    private String getStatus(int status) {
        switch (status) {
            case 401:
                return "待支付";
            case 402:
                return "未发货";
            case 403:
                return "已发货";
            case 404:
                return "已收货";
            case 405:
                return "待领取";
            default:
                return "";
        }
    }

    /**
     * 格式化TextView的显示格式，识别手机号
     */
    private SpannableStringBuilder formatPhoneNumber(TextView textView, String source) {
        // 若要部分 SpannableString 可点击，需要如下设置
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        // 将要格式化的 String 构建成一个 SpannableStringBuilder
        SpannableStringBuilder value = new SpannableStringBuilder(source);

        // 使用正则表达式匹配电话
        Linkify.addLinks(value, Pattern.compile(PATTERN_PHONE), SCHEME_TEL);

        // 获取上面到所有 addLinks 后的匹配部分(这里一个匹配项被封装成了一个 URLSpan 对象)
        URLSpan[] urlSpans = value.getSpans(0, value.length(), URLSpan.class);
        for (final URLSpan urlSpan : urlSpans) {
            if (urlSpan.getURL().startsWith(SCHEME_TEL)) {
                int start = value.getSpanStart(urlSpan);
                int end = value.getSpanEnd(urlSpan);
                value.removeSpan(urlSpan);
                value.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NotNull View widget) {
                        String phone = urlSpan.getURL().replace(SCHEME_TEL, "");
                        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                        builder.setMessage("是否拨打电话：" + phone);
                        builder.setNegativeButton("取消", null);
                        builder.setPositiveButton("确定", null);
                        builder.create().show();
                    }

                    @Override
                    public void updateDrawState(@NotNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(Color.parseColor("#3f8de2"));
                        ds.setUnderlineText(true);
                    }
                }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return value;
    }
}
